package main

import (
	"fmt"
	"github.com/iancoleman/strcase"
	"os"
	"path"
	"strings"
)

// 程序入口
func main() {
	fmt.Println(os.Args)
	doCommand(os.Args[1:])
}

// 分解命令-匹配不同方法
func doCommand(args []string) {
	if len(args) < 2 || args[0] == "-h" {
		showHelp()
		return
	}

	from := args[0]
	to := args[1]

	var newName string

	fmt.Println("from:", from)
	fmt.Println("to:", to)

	//若转化的名称第一个字符是.，则表示本次更新扩展名
	if to[0] == '.' {
		fmt.Println("扩展名更新")
		newName = doRenameExt(from, to)
	} else if to[0] == ':' {
		fmt.Println("大小写转化")
		newName = doTransform(from, to, args)
	} else {
		fmt.Println("默认文件重命名")
		newName = doRename(from, to)
	}

	err := os.Rename(from, newName)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}

}

// showHelp-展示帮助信息
func showHelp() {
	fmt.Println("renames [from] [to] [options...]")
}

// 重命名
func doRename(from, to string) string {
	//do: rename /path/a.txt to b
	//will: rename /path/a.txt to /path/b.txt

	dir := path.Dir(from)
	fmt.Println("path:", dir)

	baseName := path.Base(from)
	fmt.Println("baseName:", baseName)

	ext := path.Ext(from)
	fmt.Println("ext:", ext)

	newName := dir + "/" + to + ext
	fmt.Println("newName:", newName)
	fmt.Printf("Rename %s to %s\n", from, to)

	return newName
}

// 扩展名重命名
func doRenameExt(from, to string) string {
	dir := path.Dir(from)
	fmt.Println("path:", dir)

	baseName := path.Base(from)
	fmt.Println("baseName:", baseName)

	part := strings.Split(baseName, ".")[0]
	newExt := to

	newName := dir + "/" + part + newExt
	fmt.Println("newName:", newName)
	fmt.Printf("Rename %s to %s\n", from, to)

	return newName
}

// 名称大小写转化
func doTransform(from, to string, args []string) string {
	dir := path.Dir(from)
	fmt.Println("path:", dir)

	baseName := path.Base(from)
	fmt.Println("baseName:", baseName)

	ext := path.Ext(from)
	fmt.Println("ext:", ext)

	part := strings.Split(baseName, ".")[0]

	if to == ":upper" {
		fmt.Println("转大写")
		part = strings.ToUpper(part)
	} else if to == ":lower" {
		fmt.Println("转小写")
		part = strings.ToLower(part)
	} else if to == ":camel" {
		fmt.Println("转驼峰")
		part = strcase.ToCamel(part)
	} else if to == ":snake" {
		fmt.Println("转下划线")
		part = strcase.ToSnake(part)
	} else if to == ":plus" {
		fmt.Println("名称追加-info")
		if len(args) == 3 {
			suffix := args[2]
			part = part + suffix
		}

	}

	newName := dir + "/" + part + ext
	fmt.Println("newName:", newName)

	return newName
}
